class AddTags < ActiveRecord::Migration
  def self.up

    create_table "tags", :force => true do |t|
        t.column "name", :string, :default => "", :null => false
        t.column "created_at", :datetime
        t.column "updated_at", :datetime
    end

    create_table "pages_tags", :id => false, :force => true do |t|
        t.column "page_id", :integer, :null => false
        t.column "tag_id", :integer, :null => false
        t.column "user_id", :integer, :default => 0
        t.column "created_at", :datetime
    end

    # pages_tags
    add_index :pages_tags, :page_id
    add_index :pages_tags, :tag_id
    add_index :pages_tags, :user_id
    execute "ALTER TABLE pages_tags ADD CONSTRAINT pages_tags_page_id_fkey FOREIGN KEY (page_id) REFERENCES pages (id) ON DELETE CASCADE ON UPDATE CASCADE"
    execute "ALTER TABLE pages_tags ADD CONSTRAINT pages_tags_tag_id_fkey FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE ON UPDATE CASCADE"
    execute "ALTER TABLE pages_tags ADD CONSTRAINT pages_tags_user_id_fkey FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE"
        
  end

  def self.down
    execute "ALTER TABLE pages_tags DROP CONSTRAINT pages_tags_page_id_fkey"
    execute "ALTER TABLE pages_tags DROP CONSTRAINT pages_tags_tag_id_fkey"
    execute "ALTER TABLE pages_tags DROP CONSTRAINT pages_tags_user_id_fkey"
    
    remove_index :pages_tags, :page_id
    remove_index :pages_tags, :tag_id
    remove_index :pages_tags, :user_id

    drop_table :tags
    drop_table :pages_tags
  end

end